package com.zhkj.txg.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.txg.R
import com.zhkj.lib.config.WX_APP_ID
import com.zhkj.txg.utils.ThirdLoginEvent
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXEntryActivity : Activity(), IWXAPIEventHandler {

    private lateinit var api: IWXAPI

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID)
        api.handleIntent(intent, this)
    }

    override fun onResp(resp: BaseResp?) {
        finish()
        if (resp?.type == ConstantsAPI.COMMAND_SENDAUTH) { //  微信登录
            (resp as? SendAuth.Resp)?.let {
                when (it.errCode) {
                    // 登录成功
                    BaseResp.ErrCode.ERR_OK -> {
                        // 发送通知，告知页面已登录
                        if (it.state == "auth") RxBus.post(ThirdLoginEvent(true, it.code))
                    }
                    // 用户取消
                    BaseResp.ErrCode.ERR_USER_CANCEL -> {
                        RxBus.post(ThirdLoginEvent(false, ""))
                        ToastUtil.show(getString(R.string.third_login_cancel))
                    }
                    // 登录失败
                    else -> {
                        RxBus.post(ThirdLoginEvent(false, ""))
                        ToastUtil.show(getString(R.string.third_login_failure))
                    }
                }
            }
        }
    }

    override fun onReq(req: BaseReq?) = Unit

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api.handleIntent(intent, this)
    }
}